package common.util;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("rawtypes")
public class JSONUtil {
	
	public static <T> T parseToBean(JSONObject jsonObject, Class<T> beanCls){
		T bean = BeanUtil.newInstanceBean(beanCls);
		
		for (String fieldName : ToolUtil.getAttributes(Arrays.asList(BeanUtil.getBeanFields(beanCls)), "name", String.class)){
			if (jsonObject.has(fieldName)){
				BeanUtil.setBeanField(bean, fieldName, jsonObject.get(fieldName));
			}
		}
		return bean;
	}
	
	public static <T> List<T> parseToList(JSONArray jsonArray, Class<T> beanCls){
		List<T> result = new ArrayList<T>();
		for (int i = 0; i < jsonArray.size(); i++){
			result.add(parseToBean(jsonArray.getJSONObject(i), beanCls));
		}
		return result;
	}
	
	public static <T> T[] parseToArray(JSONArray jsonArray, Class<T> beanCls){
		return ToolUtil.collectionToArray(parseToList(jsonArray, beanCls), beanCls);
	}
	
	@SuppressWarnings("unchecked")
	public static Map parseToMap(JSONObject jsonObject){
		Map result = new HashMap();
		for (Object key : jsonObject.keySet()){
			result.put(key, jsonObject.get(key));
		}
		return result;
	}
	
	public static String format(Object obj){
		return JSONObject.fromObject(BeanUtil.parseBean(obj)).toString();
	}
	
	public static JSONObject formatBean(Object bean){
		return JSONObject.fromObject(bean);
	}
	
	public static JSONArray formatArray(Object array){
		return JSONArray.fromObject(array);
	}
	
	public static JSONArray formatArray(Collection collection){
		return JSONArray.fromObject(collection);
	}
	
	public static JSONArray formatArray(Object[] array){
		return JSONArray.fromObject(array);
	}
	
	public static JSONArray formatArray(Map map){
		return JSONArray.fromObject(map);
	}
}